package com.bjpowernode.util;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author admin
 * http 工具类
 */
public class HttpUtils {

    /**
     * 获取文件大小
     * @param url
     * @return
     * @throws IOException
     */
    public static long getHttpFileContentLength(String url) throws IOException {
        int contentLength = 0;
        HttpURLConnection httpURLConnection = null;
        try{
            httpURLConnection = getHttpURLConnection(url);
            contentLength = httpURLConnection.getContentLength();
        }finally {
            if(httpURLConnection != null){
                httpURLConnection.disconnect();
            }
        }
        return contentLength;
    }
    /**
     * 分块下载
     * @param url  下载地址
     * @param startPos 开始位置
     * @param endPos 结束位置
     * @return
     * @throws IOException
     */
    public static HttpURLConnection getHttpURLConnection(String url,long startPos,long endPos) throws IOException {
        HttpURLConnection httpURLConnection = getHttpURLConnection(url);
        LogUtils.info("下载的区间是:{} -- {}",startPos,endPos);
        if(endPos != 0){
            httpURLConnection.setRequestProperty("Range","bytes="+startPos+"-"+endPos);
        }else{
            httpURLConnection.setRequestProperty("Range","bytes="+startPos+"-");
        }
        return httpURLConnection;
    }

    /**
     * 获取http连接对象
     * @param url
     * @return
     * @throws IOException
     */
    public static HttpURLConnection getHttpURLConnection(String url) throws IOException {
        URL httpUrl = new URL(url);
        HttpURLConnection httpURLConnection = (HttpURLConnection)httpUrl.openConnection();
        httpURLConnection.setRequestProperty("User-Agent","Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
        httpURLConnection.setRequestProperty("Accept","*/*");
        httpURLConnection.setRequestProperty("Connection","Keep-Alive");
        httpURLConnection.setRequestProperty("Accept-Language","zh-CN,zh;q=0.8");
        httpURLConnection.setRequestProperty("Accept-Encoding","gzip, deflate, sdch");
        httpURLConnection.setRequestProperty("Cache-Control","max-age=0");
        httpURLConnection.setRequestProperty("Upgrade-Insecure-Requests","1");
        return httpURLConnection;
    }

    /**
     * 获取下载文件的名字
     * @param url
     * @return
     */
    //获取下载文件的名字
    public static String getHttpFileName(String url){
        int index = url.lastIndexOf("/");
        return url.substring(index+1);
    }
}
